package com.edu.servlet;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import com.edu.entity.Goods;
import com.edu.entity.Goodsimg;
import com.edu.entity.User;
import com.edu.service.impl.addGoodsServiceImpl;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

@WebServlet("/addGoods.do")
@MultipartConfig(
    fileSizeThreshold = 1024 * 1024 * 1, // 1 MB
    maxFileSize = 1024 * 1024 * 10,      // 10 MB
    maxRequestSize = 1024 * 1024 * 50    // 50 MB
)
public class addGoodsServlet extends HttpServlet {
    // 修改为相对路径
    private static final String SAVE_DIR = "C:\\poj-java\\goodimg";
    private final Gson gson = new GsonBuilder().disableHtmlEscaping().create();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        // 设置响应类型和字符编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        
        Map<String, Object> result = new HashMap<>();
        List<String> savedFileNames = new ArrayList<>();    
        ServletOutputStream out = null;
        
        try {
            // 获取实际保存路径
            String appPath = request.getServletContext().getRealPath("");
            String savePath = SAVE_DIR;
            
            // 确保保存目录存在
            File saveDir = new File(savePath);
            if (!saveDir.exists()) {
                boolean created = saveDir.mkdirs();
                if (!created) {
                    throw new IOException("无法创建图片保存目录: " + savePath);
                }
            }
            
            // 获取图片数量
            int imageCount = Integer.parseInt(request.getParameter("imageCount"));
            // 保存所有图片
            for (int i = 0; i < imageCount; i++) {
                Part filePart = request.getPart("goodsImage" + i);
                if (filePart != null && filePart.getSize() > 0) {
                    String fileName = generateUniqueFileName(filePart.getSubmittedFileName());
                    Path filePath = Paths.get(savePath, fileName);
                    Files.copy(filePart.getInputStream(), filePath);
                    savedFileNames.add("/poj-java/goodimg/"+fileName);
                }
            }
            
            // 获取session中的用户信息
			/*
			 * HttpSession session = request.getSession(); User user = (User)
			 * session.getAttribute("logInUser"); if (user == null) { result.put("success",
			 * false); result.put("message", "用户未登录"); sendJsonResponse(response, result);
			 * return; }
			 */
            HttpSession session = request.getSession();
    		User u = (User) session.getAttribute("logInUser");
            // 创建商品对象
            Goods goods = new Goods();
            goods.setGoodname(request.getParameter("goodname"));
            
            // 安全转换所有数字字段
            goods.setGoodtype(safeParseInt(request.getParameter("goodtype")));
            goods.setGoodprice(safeParseDouble(request.getParameter("goodprice")));
            goods.setOriprive(safeParseDouble(request.getParameter("oriprive")));
            goods.setGoodnum(safeParseInt(request.getParameter("goodnum")));
            goods.setGooddec(request.getParameter("gooddec"));
            goods.setGoodstat(safeParseInt(request.getParameter("goodstat")));
            goods.setGoodTradetType(safeParseInt(request.getParameter("goodTradetType")));
            goods.setGoodFreightType(safeParseInt(request.getParameter("goodFreightType")));
            goods.setSellerId(u.getUserid());	//user.getUserid());
            goods.setGoodOnSellStat(1); // 1 表示上架状态
            
            // 设置主图（第一张图片）
            if (!savedFileNames.isEmpty()) {
                goods.setGoodimg(savedFileNames.get(0));
            } else {
                result.put("success", false);
                result.put("message", "商品图片未上传");
                sendJsonResponse(response, result);
                return;
            }
            
            // 调用服务层添加商品
            addGoodsServiceImpl service = new addGoodsServiceImpl();
            int goodsId = service.addGoods(goods);
            
            if (goodsId > 0) {
                // 保存额外图片到数据库
                if (savedFileNames.size() > 1) {
                    Goodsimg goodsimg = createGoodsimg(goodsId, savedFileNames);
                    if (!service.addGoodsimg(goodsimg)) {
                        logError(new Exception("额外图片保存失败"));
                    }
                }
                result.put("success", true);
                result.put("message", "商品添加成功");
                result.put("goodsId", goodsId);
            } else {
                result.put("success", false);
                result.put("message", "商品添加失败，请检查数据");
                
                // 删除已上传的图片
                for (String fileName : savedFileNames) {
                    Files.deleteIfExists(Paths.get(savePath, fileName));
                }
            }
        } catch (Exception e) {
            logError(e);
            result.put("success", false);
            result.put("message", "服务器错误: " + e.getClass().getSimpleName() + " - " + e.getMessage());
        } finally {
            sendJsonResponse(response, result);
        }
    }
    
    private Goodsimg createGoodsimg(int goodsId, List<String> fileNames) {
        Goodsimg goodsimg = new Goodsimg();
        goodsimg.setGoodsid(goodsId);
        
        // 最多4张额外图片
        int extraCount = Math.min(fileNames.size() - 1, 4);
        for (int i = 0; i < extraCount; i++) {
            String fileName = fileNames.get(i + 1);
            switch (i) {
                case 0: goodsimg.setImg1url(fileName); break;
                case 1: goodsimg.setImg2url(fileName); break;
                case 2: goodsimg.setImg3url(fileName); break;
                case 3: goodsimg.setImg4url(fileName); break;
            }
        }
        return goodsimg;
    }
    
    // 发送JSON响应
    private void sendJsonResponse(HttpServletResponse response, Map<String, Object> result) throws IOException {
        try {
            String jsonResponse = gson.toJson(result);
            response.getWriter().write(jsonResponse);
        } catch (Exception e) {
            logError(e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "响应生成失败");
        }
    }
    
    // 安全转换整数
    private int safeParseInt(String value) {
        if (value == null || value.trim().isEmpty()) return 0;
        try {
            return Integer.parseInt(value);
        } catch (NumberFormatException e) {
            return 0;
        }
    }
    
    // 安全转换浮点数
    private double safeParseDouble(String value) {
        if (value == null || value.trim().isEmpty()) return 0.0;
        try {
            return Double.parseDouble(value);
        } catch (NumberFormatException e) {
            return 0.0;
        }
    }
    
    // 生成唯一文件名
    private String generateUniqueFileName(String originalFileName) {
        String extension = getFileExtension(originalFileName);
        return UUID.randomUUID().toString() + extension;
    }
    
    // 获取文件扩展名
    private String getFileExtension(String fileName) {
        if (fileName == null) return "";
        int dotIndex = fileName.lastIndexOf('.');
        return (dotIndex == -1) ? "" : fileName.substring(dotIndex);
    }
    
    // 记录错误日志
    private void logError(Exception e) {
        System.err.println("[" + new java.util.Date() + "] 服务器错误:");
        e.printStackTrace(System.err);
    }
}